<template>
  <div>
    <h2>图书管理</h2>
    <el-table :data="books" style="width: 100%">
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="title" label="书名"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="copies" label="副本数"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="handleDelete(scope.row.id)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-form :model="bookForm" @submit.native.prevent="handleAddBook" style="margin-top: 20px;">
      <el-form-item label="书名">
        <el-input v-model="bookForm.title"></el-input>
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="bookForm.author"></el-input>
      </el-form-item>
      <el-form-item label="副本数">
        <el-input-number v-model="bookForm.copies"></el-input-number>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAddBook">添加图书</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import booksData from '../data/books';

export default {
props: ['books'],
  name: 'BookManager',
  data() {
    return {
      books: booksData,
      bookForm: {
        title: '',
        author: '',
        copies: 0
      }
    };
  },
  methods: {
    handleAddBook() {
      if (!this.bookForm.title || !this.bookForm.author || this.bookForm.copies <= 0) {
        this.$message.error('请填写完整的图书信息');
        return;
      }
      const newBook = {
        id: this.books.length + 1,
        ...this.bookForm
      };
      this.books.push(newBook);
      this.bookForm = { title: '', author: '', copies: 0 }; // 重置表单
      this.$message.success('图书添加成功');
    },
    handleDelete(bookId) {
      const index = this.books.findIndex(book => book.id === bookId);
      if (index !== -1) {
        this.books.splice(index, 1);
        this.$message.success('图书删除成功');
      }
    }
  }
};
</script>